/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.point.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import com.jeeplus.modules.api.common.UUIDUtils;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.point.entity.Point;
import com.jeeplus.modules.point.mapper.PointMapper;

import javax.xml.crypto.Data;

/**
 * 用户积分Service
 * @author zhych
 * @version 2021-11-16
 */
@Service
@Transactional(readOnly = true)
public class PointService extends CrudService<PointMapper, Point> {

	@Autowired
	private MemberService memberService;

	public Point get(String id) {
		return super.get(id);
	}
	
	public List<Point> findList(Point point) {
		return super.findList(point);
	}
	
	public Page<Point> findPage(Page<Point> page, Point point) {
		return super.findPage(page, point);
	}
	
	@Transactional(readOnly = false)
	public void save(Point point) {
		super.save(point);
	}
	
	@Transactional(readOnly = false)
	public void delete(Point point) {
		super.delete(point);
	}

	/**
	 * 添加转入转出记录
	 * @param in 转入者
	 * @param out 转出者
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void addRecord(Member in, Member out, Integer point) {
		// 添加转入记录
		Point point2 = new Point();
		point2.setIsNewRecord(true);
		point2.setId(UUIDUtils.orderUuid(4));
		point2.setMoney(point.toString());
		point2.setPointType("1");
		point2.setInU(in);
		point2.setOutU(out);
		point2.setUpdateDate(new Date());
		super.save(point2);
		// 添加转出记录
		Point point1 = new Point();
		point1.setIsNewRecord(true);
		point1.setId(UUIDUtils.orderUuid(4));
		point1.setMoney(point.toString());
		point1.setPointType("2");
		point1.setInU(in);
		point1.setOutU(out);
		point1.setUpdateDate(new Date());
		super.save(point1);
		// 用户天畅积分的扣减与添加
		in.setTcPoint(new BigDecimal(in.getTcPoint()).add(new BigDecimal(point.toString())).setScale(2, RoundingMode.HALF_UP).toString());
		memberService.save(in);
		memberService.updateTcPoint(in);
		out.setTcPoint(new BigDecimal(out.getTcPoint()).subtract(new BigDecimal(point)).setScale(2, RoundingMode.HALF_UP).toString());
		memberService.save(out);
		memberService.updateTcPoint(out);
	}
}